package com.study.start;

import com.study.handler.NettyClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @ClassName: NettyClient
 * @Description:
 * @Date 2024/04/28 13:49
 * @Author songshaoqiu
 **/
public class NettyClient {
    public static void main(String[] args) {
        //创建线程组
        EventLoopGroup eventLoopGroup =new NioEventLoopGroup();

        try {
            //创建客户端启动对象
            Bootstrap bootstrap = new Bootstrap();
            //设置相关参数
            bootstrap.group(eventLoopGroup)
                    //使用NioSocketChannel作为客户端的通道实现
                    .channel(NioSocketChannel.class)
                    //创建通道初始化对象并设置handler业务处理器
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //添加处理器。 处理器里面是实现具体业务的
                            socketChannel.pipeline().addLast(new NettyClientHandler());
                        }
                    });
            System.out.println("客户端启动了");
            //同步阻塞的告知客户端连接的服务器地址，并启动客户端
            ChannelFuture connect = bootstrap.connect("127.0.0.1", 9090);
            //阻塞等待完成操作后 关闭通道
            connect.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            eventLoopGroup.shutdownGracefully();
        }
    }
}
